package com.sdry.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sdry.common.BaseController;
import com.sdry.common.TableDataInfo;
import com.sdry.project.entity.ProjectEntity;
import com.sdry.project.entity.ProjectExpertEntity;
import com.sdry.project.service.ProjectExpertService;
import com.sdry.project.service.ProjectService;
import com.sdry.system.entity.SysUser;
import com.sdry.untils.StringUtil;
import com.sdry.untils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version: 1.0
 * @description: 评审管理
 * @author: jyy
 * @create: 2020-8-5 16:38:41
 **/
@Controller
@RequestMapping(value = "/appraise")
public class AppraiseController extends BaseController {

    @Autowired
    private ProjectExpertService projectExpertService;
    @Autowired
    private ProjectService projectService;

    /**
     * 评审管理页面
     *
     * @return
     */
    @RequestMapping(value = "/showAppraise")
    public String showAppraise() {
        return "system/appraise/appraiseList3";
    }


    /**
     * 2020年评审管理页面2
     * @return
     */
    /*@RequestMapping(value = "/showAppraise2")
    public String showAppraise2() {
        return "/system/appraise/appraiseList2";
    }*/

    /**
     * 评审管理页面2
     *
     * @return
     */
    @RequestMapping(value = "/showAppraise2")
    public String showAppraise2() {
        return "system/appraise/appraiseList4";
    }

    /**
     * 评审管理页面2
     *
     * @return
     */
    @RequestMapping(value = "/showCharacterPrize")
    public String showCharacterPrize(Model model) {
        model.addAttribute("idea", "人物奖");
        Long userId = UserContext.getSessionUserIdByServiceImpl();
        model.addAttribute("userId", userId);
        QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(ProjectEntity::getIdea,"人物奖");
        List<ProjectEntity> list = projectService.list(queryWrapper);
        String company = "0";
        if (list.size() > 0) {
            ProjectEntity projectEntity = list.get(0);
            company = projectEntity.getCompany();
        }
        model.addAttribute("company", company);
        return "system/appraise/appraiseList4_4";
    }
    /**
     * 评审管理页面2
     *
     * @return
     */
    @RequestMapping(value = "/showFirstPrize")
    public String showFirstPrize(Model model) {
        model.addAttribute("idea", "一等奖");
        Long userId = UserContext.getSessionUserIdByServiceImpl();
        model.addAttribute("userId", userId);
        QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(ProjectEntity::getIdea,"一等奖");
        List<ProjectEntity> list = projectService.list(queryWrapper);
        String company = "0";
        if (list.size() > 0) {
            ProjectEntity projectEntity = list.get(0);
            company = projectEntity.getCompany();
        }
        model.addAttribute("company", company);
        return "system/appraise/appraiseList4_1";
    }

    /**
     * 评审管理页面2
     *
     * @return
     */
    @RequestMapping(value = "/showSecondPrize")
    public String showSecondPrize(Model model) {
        model.addAttribute("idea", "二等奖");
        Long userId = UserContext.getSessionUserIdByServiceImpl();
        model.addAttribute("userId", userId);

        QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(ProjectEntity::getIdea,"二等奖");
        List<ProjectEntity> list = projectService.list(queryWrapper);
        String company = "0";
        if (list.size() > 0) {
            ProjectEntity projectEntity = list.get(0);
            company = projectEntity.getCompany();
        }
        model.addAttribute("company", company);
        return "system/appraise/appraiseList4_2";
    }

    /**
     * 评审管理页面2
     *
     * @return
     */
    @RequestMapping(value = "/showSanPrize")
    public String showSanPrize(Model model) {
        model.addAttribute("idea", "三等奖");
        Long userId = UserContext.getSessionUserIdByServiceImpl();
        model.addAttribute("userId", userId);
        return "system/appraise/appraiseList4_3";
    }

    /**
     * 项目信息页面
     *
     * @return
     */
    @RequestMapping(value = "/showProject")
    public String showProject() {
        return "system/appraise/project";
    }

    /**
     * 根据登录用户（专家）查询所关联的项目
     *
     * @param projectExpertEntity 查询实体
     */
    @RequestMapping(value = "/selectProjectByUser")
    @ResponseBody
    public TableDataInfo selectProjectByUser(ProjectExpertEntity projectExpertEntity, HttpServletRequest httpServletRequest) {
        SysUser sysUser = (SysUser) httpServletRequest.getSession().getAttribute("user");
        PageHelper.startPage(projectExpertEntity.getPage(), projectExpertEntity.getLimit());
        projectExpertEntity.setUserId(sysUser.getUserId());

        List<ProjectExpertEntity> list = projectExpertService.listByUid(projectExpertEntity);

        PageInfo<ProjectExpertEntity> pageInfo = new PageInfo<ProjectExpertEntity>(list);
        return getDataTable(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 专家评审
     *
     * @param projectExpertEntity
     * @return 返回结果
     */
    @RequestMapping("/appraise")
    @ResponseBody
    public boolean appraise(ProjectExpertEntity projectExpertEntity, HttpServletRequest httpServletRequest) {
        SysUser sysUser = (SysUser) httpServletRequest.getSession().getAttribute("user");
        projectExpertEntity.setUpdateBy(sysUser.getUsername());
        projectExpertEntity.setUpdateDate(new Timestamp(System.currentTimeMillis()));
        Boolean b = true;
        b = projectExpertService.updateById(projectExpertEntity);
        if (b == true) {
            ProjectExpertEntity project = projectExpertService.getById(projectExpertEntity.getId());
            List<ProjectExpertEntity> list = projectExpertService.chart(project.getProjectId());
            ProjectEntity projectEntity = new ProjectEntity();
            projectEntity.setId(project.getProjectId());
            if (list.size() > 0) {
                if (list.get(0).getLevel() == 0) {
                    if (list.size() > 1) {
                        projectEntity.setAwardsresult(list.get(1).getLevel() + "");
                    } else {
                        projectEntity.setAwardsresult(list.get(0).getLevel() + "");
                    }
                } else {
                    projectEntity.setAwardsresult(list.get(0).getLevel() + "");
                }
            }
            b = projectService.updateById(projectEntity);
        }
        return b;
    }


    /**
     * 专家提交
     *
     * @return 返回结果
     */
    @RequestMapping("/booleanSubmit")
    @ResponseBody
    public Map<String, Object> booleanSubmit(String json, HttpServletRequest request) {
        ProjectExpertEntity projectExpertEntity = new ProjectExpertEntity();
        Map<String, Object> map = new HashMap<>();
        SysUser sysUser = (SysUser) request.getSession().getAttribute("user");
        projectExpertEntity.setUserId(sysUser.getUserId());
        projectExpertEntity.setIdea("二等奖");
        List<ProjectExpertEntity> list = projectExpertService.listByUid(projectExpertEntity);
        List<Long> longList = new ArrayList<>();
        for (ProjectExpertEntity expertEntity : list) {
            Long projectId = expertEntity.getProjectId();
            longList.add(projectId);
        }
        Long userId = UserContext.getSessionUserIdByServiceImpl();
        QueryWrapper<ProjectExpertEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ProjectExpertEntity::getUserId, userId);
        List<ProjectExpertEntity> list2 = projectExpertService.list(queryWrapper);

        // 查询选中的同意数量
        int index = 0;
        // 选中的id
        List<Long> longList1 = new ArrayList<>();
        List<ProjectExpertEntity> projectExpertEntityList = JSONArray.parseArray(json, ProjectExpertEntity.class);
        for (ProjectExpertEntity expertEntity : projectExpertEntityList) {
            String evaluationOpinion = expertEntity.getEvaluationOpinion();
            if ("0".equals(evaluationOpinion)) {
                index++;
            }
            Long id = expertEntity.getId();
            longList1.add(id);
        }

        for (ProjectExpertEntity expertEntity : list2) {
            if (longList.contains(expertEntity.getProjectId())) {
                if (longList1.contains(expertEntity.getId())) {
                    continue;
                }
                String evaluationOpinion = expertEntity.getEvaluationOpinion();
                if ("0".equals(evaluationOpinion)) {
                    index++;
                }
            }
        }

        QueryWrapper<ProjectEntity> queryProject = new QueryWrapper<>();
        queryProject.lambda().like(ProjectEntity::getIdea,projectExpertEntityList.get(0).getIdea());
        List<ProjectEntity> list1 = projectService.list(queryProject);
        String company = "0";
        if (list1.size() > 0) {
            ProjectEntity projectEntity = list1.get(0);
            company = projectEntity.getCompany();
            if (StringUtil.isNotEmpty(company)) {
                int i = Integer.parseInt(company);
                if (i >= index) {
                    map.put("code", 200);
                    map.put("msg", company);
                    return map;
                } else {
                    map.put("code", 100);
                    map.put("msg", company);
                    return map;
                }
            }
        }
        map.put("code", 500);
        map.put("msg", company);
        return map;
    }

    /**
     * 专家提交
     *
     * @return 返回结果
     */
    @RequestMapping("/booleanSubmit1")
    @ResponseBody
    public Map<String, Object> booleanSubmit1(String json, HttpServletRequest request) {


        ProjectExpertEntity projectExpertEntity = new ProjectExpertEntity();
        Map<String, Object> map = new HashMap<>();
        SysUser sysUser = (SysUser) request.getSession().getAttribute("user");
        projectExpertEntity.setUserId(sysUser.getUserId());
        projectExpertEntity.setIdea("一等奖");
        List<ProjectExpertEntity> list = projectExpertService.listByUid(projectExpertEntity);
        List<Long> longList = new ArrayList<>();
        for (ProjectExpertEntity expertEntity : list) {
            Long projectId = expertEntity.getProjectId();
            longList.add(projectId);
        }
        Long userId = UserContext.getSessionUserIdByServiceImpl();
        QueryWrapper<ProjectExpertEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ProjectExpertEntity::getUserId, userId);
        List<ProjectExpertEntity> list2 = projectExpertService.list(queryWrapper);

        // 查询选中的同意数量
        int index = 0;
        // 选中的id
        List<Long> longList1 = new ArrayList<>();
        List<ProjectExpertEntity> projectExpertEntityList = JSONArray.parseArray(json, ProjectExpertEntity.class);
        for (ProjectExpertEntity expertEntity : projectExpertEntityList) {
            String evaluationOpinion = expertEntity.getEvaluationOpinion();
            if ("0".equals(evaluationOpinion)) {
                index++;
            }
            Long id = expertEntity.getId();
            longList1.add(id);
        }

        for (ProjectExpertEntity expertEntity : list2) {
            if (longList.contains(expertEntity.getProjectId())) {
                if (longList1.contains(expertEntity.getId())) {
                    continue;
                }
                String evaluationOpinion = expertEntity.getEvaluationOpinion();
                if ("0".equals(evaluationOpinion)) {
                    index++;
                }
            }
        }

        QueryWrapper<ProjectEntity> queryProject = new QueryWrapper<>();
        queryProject.lambda().like(ProjectEntity::getIdea,projectExpertEntityList.get(0).getIdea());
        List<ProjectEntity> list1 = projectService.list(queryProject);
        String company = "0";
        if (list1.size() > 0) {
            ProjectEntity projectEntity = list1.get(0);
            company = projectEntity.getCompany();
            if (StringUtil.isNotEmpty(company)) {
                int i = Integer.parseInt(company);
                if (i >= index) {
                    map.put("code", 200);
                    map.put("msg", company);
                    return map;
                } else {
                    map.put("code", 100);
                    map.put("msg", company);
                    return map;
                }
            }
        }
        map.put("code", 500);
        map.put("msg", company);
        return map;
    }

    /**
     * 专家提交
     *
     * @param projectExpertEntity
     * @return 返回结果
     */
    @RequestMapping("/submit")
    @ResponseBody
    public Boolean submit(ProjectExpertEntity projectExpertEntity, HttpServletRequest httpServletRequest) {
        SysUser sysUser = (SysUser) httpServletRequest.getSession().getAttribute("user");
        projectExpertEntity.setUpdateBy(sysUser.getUsername());
        projectExpertEntity.setUpdateDate(new Timestamp(System.currentTimeMillis()));
        projectExpertEntity.setState("1");
        Boolean b = true;
        return projectExpertService.updateById(projectExpertEntity);
        //return b;
    }


    @RequestMapping("/chart")
    @ResponseBody
    public Map chart(Long pid) {
        Map map = new HashMap();

        int index = 0;

        List<ProjectExpertEntity> list = projectExpertService.chart(pid);
        if (list.size() > 0) {
            //项目类型
            map.put("type", list.get(index).getType());
            //项目评审结果
            int level = list.get(index).getLevel();

            try {
                if (level == 0) {
                    level = list.get(1).getLevel();
                    index = 1;
                }
            } catch (Exception e) {
                //e.printStackTrace();
                System.out.println("报错---评审结果--未评审");
                level = list.get(0).getLevel();
                index = 1;
            }


            String result = "";
            if (level == 0) {
                result = "未授奖";
            } else if (level == 1) {
                result = "一等奖A";
            } else if (level == 2) {
                result = "一等奖B";
            } else if (level == 3) {
                result = "一等奖C";
            } else if (level == 4) {
                result = "二等奖A";
            } else if (level == 5) {
                result = "二等奖B";
            } else if (level == 6) {
                result = "二等奖C";
            } else if (level == 7) {
                result = "三等奖A";
            }

            int temp = 0;
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getLevel() == 1) {
                    map.put("fa", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 2) {
                    map.put("fb", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 3) {
                    map.put("fc", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 4) {
                    map.put("sa", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 5) {
                    map.put("sb", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 6) {
                    map.put("sc", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 7) {
                    map.put("ta", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 8) {
                    map.put("ta1", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                } else if (list.get(i).getLevel() == 9) {
                    map.put("ta2", list.get(i).getToatol());
                    temp += list.get(i).getToatol();
                }
            }
            map.put("subtitle", "总评人数：" + temp + "  评审结果：" + result + "  评审人数：" + list.get(index).getToatol());

        }
        return map;
    }


    @RequestMapping("/chart2021")
    @ResponseBody
    public Map chart2021(Long pid) {
        Map map = new HashMap();

        int index = 0;

        List<ProjectExpertEntity> list = projectExpertService.chart2021(pid);
        if (list.size() > 0) {
            //项目类型
            map.put("type", list.get(index).getType());
            // 同意人数
            int agree = 0;
            // 不同意人数
            int notAgree = 0;
            // 评审人数
            int reviewCount = 0;
            Integer scoring = 0;
            for (ProjectExpertEntity expertEntity : list) {
                // 统计同意或者不同意人数
                if ("0".equals(expertEntity.getEvaluationOpinion())) {
                    agree++;
                } else if ("1".equals(expertEntity.getEvaluationOpinion())) {
                    notAgree++;
                }
                if (StringUtil.isNotEmpty(expertEntity.getEvaluationOpinion()) && StringUtil.isNotEmpty(expertEntity.getScoring())) {
                    reviewCount++;
                    scoring += Integer.parseInt(expertEntity.getScoring());
                }
            }
            map.put("agree", agree);
            map.put("notAgree", notAgree);

            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format((float) scoring / list.size());
            map.put("subtitle", "总评人数：" + list.size() + "  同意人数：" + agree + "  不同意人数：" + notAgree);
        }
        return map;
    }


    @RequestMapping("/chart2021_2")
    @ResponseBody
    public Map chart2021_2(Long pid) {
        Map map = new HashMap();

        int index = 0;

        List<ProjectExpertEntity> list = projectExpertService.chart2021(pid);
        if (list.size() > 0) {
            //项目类型
            map.put("type", list.get(index).getType());
            // 同意人数
            int agree = 0;
            // 不同意人数
            int notAgree = 0;
            // 评审人数
            int reviewCount = 0;
            Integer scoring = 0;
            for (ProjectExpertEntity expertEntity : list) {
                // 统计同意或者不同意人数
                if ("0".equals(expertEntity.getEvaluationOpinion())) {
                    agree++;
                } else if ("1".equals(expertEntity.getEvaluationOpinion())) {
                    notAgree++;
                }
                if (StringUtil.isNotEmpty(expertEntity.getEvaluationOpinion()) && StringUtil.isNotEmpty(expertEntity.getScoring())) {
                    reviewCount++;
                    scoring += Integer.parseInt(expertEntity.getScoring());
                }
            }
            map.put("agree", agree);
            map.put("notAgree", notAgree);

            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format((float) scoring / list.size());
            map.put("subtitle", "总评人数：" + list.size() + "  同意人数：" + agree + "  不同意人数：" + notAgree);
        }
        return map;
    }

    public static void main(String[] args) {
        for (int i = 30495; i <= 30561; i++) {


            String str = "INSERT INTO [dbo].[project_expert] ([project_id], [user_id], [level], [create_date], [create_by], [del_flag], [update_date], [update_by], [state], [evaluation_opinion], [scoring]) VALUES ("+i+", 58, 0, '2021-12-14 13:18:16.447', '王猛', '0 ', NULL, NULL, NULL, NULL, NULL);\n" +
                    "INSERT INTO [dbo].[project_expert] ([project_id], [user_id], [level], [create_date], [create_by], [del_flag], [update_date], [update_by], [state], [evaluation_opinion], [scoring]) VALUES ("+i+", 60, 0, '2021-12-14 13:18:16.460', '王猛', '0 ', NULL, NULL, NULL, NULL, NULL);\n" +
                    "INSERT INTO [dbo].[project_expert] ([project_id], [user_id], [level], [create_date], [create_by], [del_flag], [update_date], [update_by], [state], [evaluation_opinion], [scoring]) VALUES ("+i+", 61, 0, '2021-12-14 13:18:16.467', '王猛', '0 ', NULL, NULL, NULL, NULL, NULL);\n" +
                    "INSERT INTO [dbo].[project_expert] ([project_id], [user_id], [level], [create_date], [create_by], [del_flag], [update_date], [update_by], [state], [evaluation_opinion], [scoring]) VALUES ("+i+", 62, 0, '2021-12-14 13:18:16.480', '王猛', '0 ', NULL, NULL, NULL, NULL, NULL);\n" +
                    "INSERT INTO [dbo].[project_expert] ([project_id], [user_id], [level], [create_date], [create_by], [del_flag], [update_date], [update_by], [state], [evaluation_opinion], [scoring]) VALUES ("+i+", 63, 0, '2021-12-14 13:18:16.490', '王猛', '0 ', NULL, NULL, NULL, NULL, NULL);\n" +
                    "INSERT INTO [dbo].[project_expert] ([project_id], [user_id], [level], [create_date], [create_by], [del_flag], [update_date], [update_by], [state], [evaluation_opinion], [scoring]) VALUES ("+i+", 64, 0, '2021-12-14 13:18:16.503', '王猛', '0 ', NULL, NULL, NULL, NULL, NULL);\n";

            System.out.println(str);
        }

    }
}
